package com.ljp.makefriend.aspect;

import com.ljp.makefriend.common.ErrorCode;
import com.ljp.makefriend.exception.BusinessException;
import com.ljp.makefriend.pojo.User;
import com.ljp.makefriend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 仅允许管理员新增标签的切面
 */
@Aspect
@Component
@Slf4j
public class AdminTagCreationAspect {

    @Resource
    private UserService userService;

    /**
     * 针对新增标签接口进行拦截
     */
    @Pointcut("execution(* com.ljp.makefriend.controller.UserTagController.addTag(..))")
    public void addTagEndpoint() {}

    /**
     * 方法执行前检查是否为管理员
     */
    @Before("addTagEndpoint()")
    public void checkAdminBeforeAddTag(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        if (args.length < 2 || !(args[1] instanceof HttpServletRequest)) {
            // 方法签名发生变化或未按约定传递 request
            log.warn("AddTag 接口参数不符合预期，无法获取 HttpServletRequest");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统配置异常");
        }
        HttpServletRequest request = (HttpServletRequest) args[1];
        // 获取并校验登录用户
        User loginUser = userService.getLoginUser(request); // 未登录会抛 BusinessException
        boolean isAdmin = userService.isAdmin(loginUser);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH, "仅管理员可创建标签");
        }
    }
}